package com.twohand.admin.Util;

import com.twohand.utils.Response.BaseException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Component
@Data
public class ExcelReader {
    String[] imageSuffix = {"png","jpg","gif"};
    Date nowDate = new Date();
    SimpleDateFormat year = new SimpleDateFormat("yyyy");
    SimpleDateFormat month = new SimpleDateFormat("MM");
    String typePath = "images/avatar";
    //文件保存位置
    @Value("${custom.saveStaticPath}")
    public String saveStaticPath;
    //静态访问路径
    @Value("${custom.staticPath}")
    public String staticPath;
    public Map<String, List<String>> read(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        Workbook workbook = null;
        InputStream inputStream = file.getInputStream();
        Map<String, List<String>> map = new HashMap<>();
        log.info("文件名：{}",fileName);
        if (fileName.endsWith("xls")) {
            // 2003
            workbook = new HSSFWorkbook(inputStream);
            HSSFSheet hssfSheet = (HSSFSheet) workbook.getSheetAt(0);
            try{
                map = getPicturesMap(hssfSheet);
            }catch (NullPointerException | ClassCastException e){

            }

        } else if (fileName.endsWith("xlsx")) {
            // 2007
            workbook = new XSSFWorkbook(inputStream);
            XSSFSheet xssfSheet = (XSSFSheet) workbook.getSheetAt(0);
            try{
                map = getPicturesMap(xssfSheet);
            }catch (NullPointerException | ClassCastException e){

            }
        }

        return map;
    }
    //xlsx版
    public Map<String, List<String>> getPicturesMap(XSSFSheet xssfSheet){
        Map<String,List<String>> map = new HashMap<>();
        List<XSSFShape> list =xssfSheet.getDrawingPatriarch().getShapes();
        log.info("xlsx shape个数:{}",String.valueOf(list.size()));
        for (XSSFShape shape:list) {
            try{
                XSSFPicture picture = (XSSFPicture) shape;
                XSSFClientAnchor xssfClientAnchor=(XSSFClientAnchor) picture.getAnchor();
                XSSFPictureData pdata = picture.getPictureData();
//                System.out.println(pdata);
                Integer row = xssfClientAnchor.getRow1();
                Short col = xssfClientAnchor.getCol1();
                String rowKey = String.valueOf(row);
                if(!map.containsKey(rowKey)){
                    map.put(rowKey,new ArrayList<String>());
                }
                String suffix = pdata.getMimeType().split("/")[1];
                String path = saveImage(pdata.getData(),"."+suffix);
//                log.info("文件后缀名:{}",suffix);
                map.get(rowKey).add("default://"+path);
            }catch (NullPointerException | ClassCastException | IOException e){
//                e.printStackTrace();
            }
        }
        return map;
    }
    //读取xls版
    public Map<String, List<String>> getPicturesMap(HSSFSheet hssfSheet){
        Map<String,List<String>> map = new HashMap<>();
        List<HSSFShape> list =hssfSheet.getDrawingPatriarch().getChildren();
        log.info("xls  shape个数:{}",String.valueOf(list.size()));
        for (HSSFShape shape:list) {
            try{
                HSSFPicture picture = (HSSFPicture) shape;
                HSSFClientAnchor hssfClientAnchor=(HSSFClientAnchor) picture.getClientAnchor();
                PictureData pdata = picture.getPictureData();
//                System.out.println(pdata);
                Integer row = hssfClientAnchor.getRow1();
                Short col = hssfClientAnchor.getCol1();
                String rowKey = String.valueOf(row);
                if(!map.containsKey(rowKey)){
                    map.put(rowKey,new ArrayList<String>());
                }
                String suffix = pdata.getMimeType().split("/")[1];
                String path = saveImage(pdata.getData(),"."+suffix);
//                log.info("文件后缀名:{}",suffix);
                map.get(rowKey).add("default://"+path);
            }catch (NullPointerException | ClassCastException | IOException e){
//                e.printStackTrace();
            }
        }
        return map;
    }
    public  String saveImage(byte[] data,String fileSuffix) throws IOException {
        //文件后缀
        String basePath = getPath(typePath);
        String filename = String.valueOf(UUID.randomUUID()) + fileSuffix;
        //创建文件夹
        File fileExist = new File(basePath);
        if(!fileExist.exists()){
            Boolean mk = fileExist.mkdirs();
        }
        File file = new File(basePath,filename);
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(data);
        fileOutputStream.close();
        return getSavePath(typePath) +filename;
    }
    public String getPath(String type) throws IOException {
        File file = new File(saveStaticPath);
        return file.getCanonicalPath()+this.getSavePath(type);
    }
    public String getSavePath(String type){
        return staticPath+"upload/"+type+"/"+year.format(nowDate)+month.format(nowDate) + "/";
    }
}
